package com.durian.base.utils.task;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * 说明：TaskRunnable
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019-12-18 15:26
 * <p/>
 * 版本：version 1.0
 */
public abstract class TaskRunnable implements Callable,LifecycleObserver {

    private Future mFuture;
    private LifecycleOwner mLifecycleOwner;

    public void init(LifecycleOwner lifecycleOwner,Future future) {
        mLifecycleOwner = lifecycleOwner;
        mFuture = future;
        lifecycleOwner.getLifecycle().addObserver(this);
    }

    public abstract void executeTask();

    public void onCancel(){}

    public void onDestroy(){}

    @Override
    public Object call() throws Exception {
        executeTask();
        return null;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public final void destroy(){
        doCancel();
        onDestroy();
    }

    public final boolean isDone(){
        return mFuture == null ? false : mFuture.isDone();
    }

    public final boolean isCancelled(){
        return mFuture == null ? false : mFuture.isCancelled();
    }

    private void doCancel(){
        if (mLifecycleOwner != null){
            mLifecycleOwner.getLifecycle().removeObserver(this);
            mLifecycleOwner = null;
        }
        if (mFuture != null && !mFuture.isCancelled()){
            mFuture.cancel(true);
        }
    }

    public final void cancelTask(){
        doCancel();
        onCancel();
    }

    public final boolean isRunning(){
        if (isDone() || isCancelled()){
            return false;
        }else {
            return true;
        }
    }
}
